package com.kkb.kkbauth.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kkb.kkbauth.dao.UserMapper;
import com.kkb.kkbauth.domain.Role;
import com.kkb.kkbauth.domain.User;
import com.kkb.kkbauth.domain.UserRole;
import com.kkb.kkbauth.service.RoleService;
import com.kkb.kkbauth.service.UserRoleService;
import com.kkb.kkbauth.service.UserService;
import com.kkb.kkbcommon.exception.Asserts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;


/**
 * @author
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private RoleService roleService;

    @Autowired
    private UserRoleService userRoleService;

    /**
     * 根据用户姓名得到用户对象
     * @param userName 用户姓名
     * @return 用户对象
     */
    @Override
    public User getByUserName(String userName) {
        User user = this.lambdaQuery().eq(User::getName, userName).one();
        if (user == null){
            Asserts.fail("未查找到该用户");
        }
        return user;
    }

    /**
     * 根据用户id，查询对应的角色信息
     * @param userId 用户id
     * @return 角色列表
     */
    @Override
    public List<Role> selectRolesByUserId(Long userId) {

        // 1. 根据用户id，查找对应的用户角色列表
        List<UserRole> userRoleList = userRoleService.lambdaQuery().eq(UserRole::getUserId, userId).list();
        if (CollUtil.isEmpty(userRoleList)){
            Asserts.fail("未查找到userId="+userId+"，对应的用户角色列表");
        }

        ArrayList<Role> roleList = new ArrayList<>();
        for (UserRole userRole : userRoleList){
            Long roleId = userRole.getRoleId();
            Role role = roleService.getById(roleId);
            roleList.add(role);
        }

        return roleList;
    }

}
